package com.lanou.wuyou.gift.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.lanou.wuyou.gift.R;
import com.lanou.wuyou.gift.ormLite.Search;
import com.lanou.wuyou.gift.ormLite.SearchDao;

import java.util.List;

/**
 * Created by dllo on 17/4/6.
 */

public class HomeFirstSearchHistory extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemLongClickListener {
    private ListView listView;
    private EditText editText;
    private TextView textView;
    private HomeFirstSearchHistoryAdapter adapter;
    private List<Search> searches1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_search_history);
        listView = (ListView) findViewById(R.id.home_search_lv);
        editText = (EditText) findViewById(R.id.home_search_et);
        textView = (TextView) findViewById(R.id.home_search_tv);
        adapter = new HomeFirstSearchHistoryAdapter(this);
        listView.setAdapter(adapter);
        textView.setOnClickListener(this);
        listView.setOnItemLongClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String content = editText.getText().toString();
        List<Search> searches = SearchDao.getsTnstance(HomeFirstSearchHistory.this).queryAll();
        if (content.length() > 0){
            for (Search search : searches){
                if (content.equals(search.getContent())){
                    SearchDao.getsTnstance(HomeFirstSearchHistory.this).deleteOne(search.getContent());
                }
            }
        }
        long time = System.currentTimeMillis();
        Search search = new Search();
        search.setContent(content);
        search.setTime(time + "");

        SearchDao.getsTnstance(HomeFirstSearchHistory.this).add(search);
        searches1 = SearchDao.getsTnstance(HomeFirstSearchHistory.this).queryAll();
        adapter.setSearches(searches1);
        editText.setText("");
        }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        String content = searches1.get(position).getContent();
        SearchDao.getsTnstance(HomeFirstSearchHistory.this).deleteOne(content);
        List<Search> searches = SearchDao.getsTnstance(HomeFirstSearchHistory.this).queryAll();
        adapter.setSearches(searches);
        return false;
    }
}
